<?php
/**
 * 匠言知识付费
 * Author: 山西匠言网络科技有限公司
 * This is not a free software, it under the license terms, you can visit https://www.zsffzxkc.cn/ get more details.
 */
if(file_exists('./install.lock')){
    header("Location: ../index.php");
    exit();
}
session_start();
const EXT_NAME = 'swoole_loader';
const WIZARD_VERSION = '3.1';
const DOWNLOAD_URL = 'https://compiler.swoole.com/encryptor/download/';
function swoole_loader_is_thread_safety()
{
    ob_start();
    phpinfo();
    $phpInfo = strip_tags(ob_get_contents());
    ob_end_clean();
    if (php_sapi_name() == 'cli') {
        return !preg_match_all('#Thread\s+Safety\s+\=\>\s+disabled#i', $phpInfo, $match);
    } else {
        return !preg_match_all('#Thread\s+Safety\s+disabled#i', $phpInfo, $match);
    }
}

function swoole_loader_get_info()
{
    $env = [];
    // Check os type
    $env['os'] = [];
    $env['os']['name'] = PHP_OS;
    $env['os']['raw_name'] = php_uname();
    $env['os']['is_win'] = strtolower(substr(PHP_OS, 0, 3)) === 'win';
    $env['loader_ext'] = $env['os']['is_win'] ? 'dll' : 'so';
    // Check php
    $env['php'] = [];
    $env['php']['version'] = phpversion();
    $php_version = substr($env['php']['version'],0,3);
    if ($php_version == 7.1){
        $env['php']['is_version_ok'] = 0;
    }else{
        $env['php']['is_version_ok'] = 1;
    }
    // Check run mode
    $sapi_type = php_sapi_name();
    if ("cli" == $sapi_type) {
        $env['php']['run_mode'] = "cli";
    } else {
        $env['php']['run_mode'] = "web";
    }
    // Check php bit
    if (PHP_INT_SIZE == 4) {
        $env['php']['bit'] = 32;
    } else {
        $env['php']['bit'] = 64;
    }
    $env['php']['sapi'] = $sapi_type;
    $env['php']['ini_loaded_file'] = php_ini_loaded_file() ?: '(none)';
    $env['php']['ini_scanned_files'] = php_ini_scanned_files() ?: '(none)';
    $env['php']['loaded_extensions'] = get_loaded_extensions();
    $env['php']['incompatible_extensions'] = ['xdebug', 'ionCube', 'zend_loader', 'swoole_tracker'];
    $env['php']['loaded_incompatible_extensions'] = [];
    $env['php']['extension_dir'] = ini_get('extension_dir');
    // Check incompatible extensions
    if (is_array($env['php']['loaded_extensions'])) {
        foreach ($env['php']['loaded_extensions'] as $loaded_extension) {
            foreach ($env['php']['incompatible_extensions'] as $incompatible_extension) {
                if (strpos(strtolower($loaded_extension), strtolower($incompatible_extension)) !== false) {
                    $env['php']['loaded_incompatible_extensions'][] = $loaded_extension;
                }
            }
        }
    }
    $env['php']['loaded_incompatible_extensions'] = array_unique($env['php']['loaded_incompatible_extensions']);
    // Check php thread safety
    $env['php']['thread_safety'] = swoole_loader_is_thread_safety() ? '线程安全' : '非线程安全';
    // Check swoole loader installation
    if (extension_loaded(EXT_NAME)) {
        $env['php']['swoole_loader']['status'] = "<span style='color: #007bff;'>已安装</span>";
        $env['php']['swoole_loader']['version'] = "<span style='color: #007bff;'>" . swoole_loader_version() . "</span>";
    } else {
        $env['php']['swoole_loader']['status'] = '未安装';
        $env['php']['swoole_loader']['version'] = '未知';
    }
    $pre = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'swoole_download'. DIRECTORY_SEPARATOR;
    $swoole_download_all_urls = [
        'windows' => [
            $pre.'swoole_loader_71_nts.dll',
            $pre.'swoole_loader_71_zts.dll'
        ],
        'Linux' => [
            $pre.'swoole_loader71.so',
            $pre.'swoole_loader71_zts.so'
        ]
    ];
    if($env['os']['is_win'] == true){
        $swoole_download_url = $env['php']['thread_safety'] == '非线程安全'?$swoole_download_all_urls['windows'][0]:$swoole_download_all_urls['windows'][1];
    }else{
        $swoole_download_url = $env['php']['thread_safety'] == '非线程安全'?$swoole_download_all_urls['Linux'][0]:$swoole_download_all_urls['Linux'][1];
    }
    $env['swoole']['swoole_download_url'] = $swoole_download_url;
    return $env;
}
function insert_phpIni_data(){
    $env = $_SESSION['env'];
    $data = '
[swoole_loader]
extension='.$env['swoole']['load_name'].'
swoole_loader.license_files='.$env['swoole']['license_path'];
    return $data;
}
function insert_phpIni_data1(){
    $env = $_SESSION['env'];
    $data = '
[swoole_loader] <br>
extension='.$env['swoole']['load_name'].' <br>
swoole_loader.license_files='.$env['swoole']['license_path'];
    return $data;
}
if (!function_exists('swoole_loader_version')) {
    function swoole_loader_version(){
        return '3.0.3';
    }
}
if($_POST['form']=='formSwoole'){
    ini_set("display_errors", "On");
    error_reporting(E_ALL);
    restore_exception_handler();
    restore_error_handler();
    date_default_timezone_set('Asia/Shanghai');

    $env = swoole_loader_get_info();
    $_SESSION['env'] = $env;
    echo json_encode(['code'=>0,'msg'=>'环境检测成功', 'data' => $env]);
}
if($_POST['form']=='swoole_install'){
    $env = $_SESSION['env'];
    $source_file = $env['swoole']['swoole_download_url'];
    $dir=dirname($source_file);
    $license_path = __DIR__. DIRECTORY_SEPARATOR .'swoole-compiler.license';
    $fileName= basename($source_file);  //获取swoole文件名
    $_SESSION['env']['swoole']['license_path'] = $license_path;
    $_SESSION['env']['swoole']['load_name'] = $fileName;
    $install_path = $env['php']['extension_dir'];
    if($env['os']['is_win'] == true){
        if(file_exists($install_path)){
            $res = copy($source_file,$install_path.DIRECTORY_SEPARATOR.$fileName);
            if($res == 1){
                $fp= fopen($env['php']['ini_loaded_file'], "a+");
                $insert_data = insert_phpIni_data();
                $len = fwrite($fp, $insert_data);
                fclose($fp);
                echo json_encode(['code'=>0,'msg'=>'swoole安装成功,请重启php-fpm服务,并刷新此页面']);
            }
        }else{
            echo json_encode(['code'=>1,'msg'=>'目录不存在']);
        }
    }else{
        $insert_data = insert_phpIni_data1();
        $file = '
            <span>cp -f '.$env['swoole']['swoole_download_url'].' '.$install_path.DIRECTORY_SEPARATOR.$fileName.' </span>
            <br>
            <span>echo "'.$insert_data.'">>'.$env['php']['ini_loaded_file'].' </span> 
            <br>
            <span>echo "swoole_loader install ok "</span>
        ';
        $fp= fopen('.'.DIRECTORY_SEPARATOR.'swoole_install.sh', "w+");
        $len = fwrite($fp, $file);
        fclose($fp);
        echo json_encode(['code'=>0,'msg'=>'<h2>√恭喜您，swoole_loader安装脚本已生成请按以下步骤进行操作</h2> <h3 style="margin-top: 20px;color: red;">1.linux环境请在宝塔面板终端或者SSH终端复制以下脚本进行安装</h3>','data'=>$file]);
    }
}
/*swoole 扩展检测*/

if($_POST['form']=='form1'){
    $_POST['port']=$_POST['port']!=''?$_POST['port']:'3306';
    $con= @mysqli_connect($_POST['hostname'],$_POST['username'],$_POST['password'],$_POST['database'],$_POST['port']);  //连接数据库
    if(!$con){
        $message = sprintf(
            "连接数据库失败，请检查: %s",
            mysqli_connect_error()
        );
        trigger_error($message);
    }else{
        $_SESSION['hostname']=$_POST['hostname'];
        $_SESSION['database']=$_POST['database'];
        $_SESSION['username']=$_POST['username'];
        $_SESSION['password']=$_POST['password'];
        $_SESSION['pre']=$_POST['pre']!=''?$_POST['pre']:'jy_';
        $_SESSION['port']=$_POST['port'];
        echo json_encode(['code'=>0,'msg'=>'<div style="color: #00B83F;">√连接成功</div>']);
    }
}
if($_POST['form']=='form2'){
    $env = $_SESSION['env'];
    $result = [];
    //检测sql文件是否存在
    $filename = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR."zsffzxkc.sql";
    if(file_exists($filename)){
        $result['sql_code'] = 0;
    }else{
        $result['sql_code'] = 1;
    }
    //检测文件读写权限
    $path= dirname(dirname(dirname(__FILE__))) .DIRECTORY_SEPARATOR. 'application';
    if(is_writable($path)){
        $result['path_code'] = 0;
    }else{
        $result['path_code'] = 1;
    }
    //检测php版本环境
    $php_version = substr(PHP_VERSION,0,3);
    if ($php_version == 7.1){
        $result['php_version'] = 0;
    }else{
        $result['php_version'] = 1;
    }
    echo json_encode(['code'=>0,'msg'=>"安装环境检测完成",'data' =>$result]);
}
if($_POST['form']=='form3'){
    $data ="<?php
            return [
                // 数据库类型
                'type'            => 'mysql',
                // 服务器地址
                'hostname'        => '{$_SESSION['hostname']}',
                // 数据库名
                'database'        => '{$_SESSION['database']}',
                // 用户名
                'username'        => '{$_SESSION['username']}',
                // 密码
                'password'        => '{$_SESSION['password']}',
                // 端口
                'hostport'        => '{$_SESSION['port']}',
                // 连接dsn
                'dsn'             => '',
                // 数据库连接参数
                'params'          => [],
                // 数据库编码默认采用utf8
                'charset'         => 'utf8',
                // 数据库表前缀
                'prefix'          => '{$_SESSION['pre']}',
                // 数据库调试模式
                'debug'           => true,
                // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
                'deploy'          => 0,
                // 数据库读写是否分离 主从式有效
                'rw_separate'     => false,
                // 读写分离后 主服务器数量
                'master_num'      => 1,
                // 指定从服务器序号
                'slave_no'        => '',
                // 是否严格检查字段是否存在
                'fields_strict'   => true,
                // 数据集返回类型
                'resultset_type'  => '\\think\Collection',
                // 自动写入时间戳字段
                'auto_timestamp'  => true,
                // 时间字段取出后的默认时间格式
                'datetime_format' => 'Y-m-d H:i',
                // 是否需要进行SQL性能分析
                'sql_explain'     => true,
                // 开启断线重连
                'break_reconnect' => true,
            ];";
    $numbytes = file_put_contents(__DIR__ . '/../../application/database.php', $data); //如果文件不存在创建文件，并写入内容
    if($numbytes){
        $mysqli = new mysqli($_SESSION['hostname'],$_SESSION['username'],$_SESSION['password'],$_SESSION['database'],3306);  //连接数据库
        if($mysqli){
            $query = file_get_contents(__DIR__.'/../zsffzxkc.sql');
            if($query){
                //执行多条SQL语句
                if($mysqli->multi_query($query)){
                    echo json_encode(['code'=>0,'msg'=>'<div style="color: #00B83F;">√安装成功</div>']);
                    file_put_contents(__DIR__ . '/install.lock', '匠言知识付费安装锁定文件,请勿删除');
                }else{
                    $message = sprintf(
                        "安装失败，请检查: %s",
                        $mysqli->error
                    );
                    trigger_error($message);
                }
            }else{
                echo json_encode(['code'=>1,'msg'=>'public目录下sql文件不存在']);
            }
            $mysqli->close();//关闭mysqli连接
        }else{
            $message = sprintf(
                "数据库连接失败，请检查: %s",
                $mysqli->errno."---".$mysqli->error
            );
            trigger_error($message);
        }
    }else{
        echo json_encode(['code'=>1,'msg'=>'权限不足,写入失败']);
    }
}